package com.zookeeper.curator;

import com.zookeeper.utils.ConnectionUtil;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.cache.CuratorCache;
import org.apache.curator.framework.recipes.cache.CuratorCacheListener;

import java.io.IOException;

/**
 * @Author 咕唧
 * @Date 2022/7/2 19:49
 * @Version 1.0
 */
public class CuratorListener {
    public static void main(String[] args) throws IOException {
        CuratorFramework framework = ConnectionUtil.getFramework();

        CuratorCache curatorCache = CuratorCache.builder(framework, "/test").build();
        //设置监听器
        CuratorCacheListener cacheListener = CuratorCacheListener.builder()
                //给节点设置监听
                .forCreates(node -> {
                    //创建节点
                    String path = node.getPath();
                    byte[] data = node.getData();
                    System.out.println("创建节点：" + path + "节点数据" + new String(data));
                }).forChanges((childData, childData1) -> {
                    byte[] data = childData.getData();
                    byte[] data1 = childData1.getData();
                    System.out.println("节点变化前的数据：" + new String(data) + "节点变化后的数据：" + new String(data1));
                }).forDeletes(childData -> {
                    System.out.println(childData.getPath() + "节点被删除了");
                }).forAll((type, oldData, data) -> {
                    switch (type) {
                        //改变
                        case NODE_CHANGED:
                            break;
                        //创建
                        case NODE_CREATED:
                            break;
                        //删除
                        case NODE_DELETED:
                            break;
                    }
                }).build();
        //添加监听
        curatorCache.listenable().addListener(cacheListener);
        //启动监听
        curatorCache.start();

        System.in.read();
    }
}
